package com.live.task;

import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import com.live.activity.R;
import com.live.adapter.LiveSearchSA;
import com.live.common.Constant;
import com.live.tools.LiveTools;

public class LiveSearch extends AsyncTask<String, Integer, String> {

	private Context context;

	private LiveSearchSA adapter;

	private List<Map<String, Object>> list;

	private List<Map<String, Object>> listTmp;

	private View liveSearchFoot;

	private ListView listView;

	private String locale = LiveTools.getLocaleLanguage();

	private Dialog proDialog;

	public LiveSearch(Context context, LiveSearchSA adapter, List<Map<String, Object>> list, ListView listView,
			View liveSearchFoot) {
		this.context = context;
		this.adapter = adapter;
		this.list = list;
		this.listView = listView;
		this.liveSearchFoot = liveSearchFoot;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		Log.i("PageTask", "onPreExecute()  " + Thread.currentThread().getId());
		proDialog = new Dialog(context, R.style.progress_dialog);
		proDialog.setContentView(R.layout.live_progress_dialog);
		proDialog.show();
	}

	@Override
	protected String doInBackground(String... params) {

		Log.i("PageTask", "doInBackground... " + Thread.currentThread().getId());
		listTmp = getServerData(params[0]);
		list.addAll(listTmp);
		return null;
	}

	@Override
	protected void onPostExecute(String result) {
		Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());
		proDialog.dismiss();

		if (listTmp.size() < Constant.PAGE_SIZE) {
			listView.removeFooterView(liveSearchFoot);
		}

		adapter.notifyDataSetChanged();
	}

	public List<Map<String, Object>> getServerData(String url) {
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		HttpClient client = new DefaultHttpClient();
		try {
			HttpGet request = new HttpGet(new URI(url));
			request.addHeader("Accept-Encoding", "gzip");
			HttpResponse response = client.execute(request);

			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();

				if (entity != null) {
					String out = null;
					InputStream is = entity.getContent();
					if (entity.getContentEncoding().getValue().contains("gzip")) {
						out = LiveTools.isToString(is);
					} else {
						out = EntityUtils.toString(entity);
					}
					try {
						String result = new JSONObject(out).getString("result");
						if (Constant.Y.equals(result)) {
							JSONArray matches = new JSONObject(out).getJSONArray("results");
							for (int i = 0; i < matches.length(); i++) {
								Map<String, Object> map = new HashMap<String, Object>();
								String matchTime = (String) matches.getJSONObject(i).get("matchTime");
								map.put("matchId", matches.getJSONObject(i).get("matchId"));
								map.put("matchOptaId", matches.getJSONObject(i).get("matchOptaId"));
								map.put("matchName", LiveTools.tradToSimp(matches.getJSONObject(i).get("matchName")
										.toString(), locale));
								map.put("matchCategory", matches.getJSONObject(i).get("matchCategory"));
								map.put("matchTime", matchTime.substring(2, 10) + "\n" + matchTime.substring(11, 16));
								map.put("matchTimeAll", matchTime);
								map.put("homeTeam",
										LiveTools.tradToSimp(matches.getJSONObject(i).get("homeTeam").toString()
												.replace("?", "·"), locale));
								map.put("homeTeamName", matches.getJSONObject(i).get("homeTeamName").toString()
										.replace("?", "·"));
								map.put("homeTeamScore", matches.getJSONObject(i).get("homeTeamScore"));
								map.put("homeTeamPic", matches.getJSONObject(i).get("homeTeamPic"));
								map.put("visitTeam",
										LiveTools.tradToSimp(matches.getJSONObject(i).get("visitTeam").toString()
												.replace("?", "·"), locale));
								map.put("visitTeamName", matches.getJSONObject(i).get("visitTeamName").toString()
										.replace("?", "·"));
								map.put("visitTeamScore", matches.getJSONObject(i).get("visitTeamScore"));
								map.put("visitTeamPic", matches.getJSONObject(i).get("visitTeamPic"));
								if ("实录".equals(matches.getJSONObject(i).get("matchRecord").toString())
										|| "直播间".equals(matches.getJSONObject(i).get("matchRecord").toString())) {
									map.put("matchStatus", matches.getJSONObject(i).get("matchStatus"));
									map.put("matchRecord", "●");
								} else {
									if (Constant.MATCH_STATUS_3.equals(matches.getJSONObject(i).get("matchStatus")
											.toString())) {
										map.put("matchStatus", Constant.MATCH_STATUS_2);
									} else {
										map.put("matchStatus", matches.getJSONObject(i).get("matchStatus"));
									}
									map.put("matchRecord", null);
								}
								map.put("matchStatus", LiveTools.tradToSimp(map.get("matchStatus").toString(), locale));
								map.put("matchWatch", matches.getJSONObject(i).get("matchWatch"));
								data.add(map);
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			Toast.makeText(context, "远程服务器无响应，请稍候再试！", Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}
		return data;
	}
}